﻿#include "user.h"
#include<QDir>
#include<QJsonDocument>

QMap<QString,QString> User::map;
User* User::cUser=nullptr;


bool User::login(QString name, QString password)
{
    if(iflogin){
        emit sendMsg("please logout first");
        return false;
    }
    else{
        QString path = getuserfolder(name);
        QDir dir;
        if(dir.exists(path)){
            path = getuserfile(name);
            QFile file(path);
            if(file.exists()){
                QJsonObject obj = readjsonobj(path);
                if(obj.value(PSW).toString() == password){
                    remove_history_bookmark();
                    setCharater(name);
                    iflogin = true;
                    emit sendMsg("welcome " + name);
                    emit userChanged();
                    emit logStatusChanged();
                }
                else{
                    emit sendMsg("your password wrong");
                }
            }
            else{
                emit sendMsg("do not find the user you need");
                return false;
            }
        }
        else{
            emit sendMsg("do not find the user need");
            return false;
        }
    }
    return false;
}

void User::logout()
{

    if(!iflogin){
        emit sendMsg("you should login first default_user!");
        return;
    }
    sendMsg("Goodbye " + m_name);
    remove_history_bookmark();
    QString p = "default_user";
    setCharater(p);
    iflogin = false;
    emit userChanged();
    emit logStatusChanged();
}



User::User()
{
    QString p = "default_user";
    QString path = getuserfolder(p);
    qDebug()<<path;
    QDir dir;
    if(!dir.exists(path))
    {
        dir.mkpath(path);
        qDebug()<<"here";
    }
    path = getuserfile(p);
    QFile f(path);
    if(!f.exists()){
        m_name = p;
        m_password = "";
        m_downloadFolder = downloadPath;
        m_profile = "";
        saveMesage();
    }
    m_historyManager = NULL;
    m_bookmarkManager = NULL;
    m_downloadManager=NULL;
    setCharater(p);
    iflogin = false;
    emit logStatusChanged();
    QString str = QDir::currentPath() + "/config.txt";
    QFile file(str);

    if(file.exists()){
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QString name = in.readLine();
            QString psw = in.readLine();
            login(name,psw);
        }

    }
}

User::User(QString name,QString password):m_name(name),m_password(password)
{
    User();
    //暂时没有用到的函数
}

User::~User()
{
    //    delete m_historyManager;
    //    delete m_bookmarkManager;
    //    m_historyManager = nullptr;
    //    m_bookmarkManager = nullptr;
    //todo：发现bug，如果删除全部后，文件可能有部分没删完整
    remove_history_bookmark();
    QString str = QDir::currentPath() + "/config.txt";
    QFile file(str);
    file.remove();
    if(iflogin){
        if(!file.open(QIODevice::WriteOnly))
        {
            return;
        }

        QTextStream fileOut(&file);
        // fileOut.setCodec("UTF-8");  //unicode UTF-8  ANSI
        fileOut << m_name<<"\n";
        fileOut << m_password<<"\n";
        file.flush();
        file.close();
    }
}


HistoryManager* User::historyManager() const
{
    return m_historyManager;
}

BookmarkManager* User::bookmarkManager() const
{
    return m_bookmarkManager;
}

DownLoadManager *User::downloadManager() const
{
    return m_downloadManager;
}

QString User::name() const
{
    return m_name;
}

QString User::password() const
{
    return m_password;
}

bool User::logStatus()const
{
    return iflogin;
}

QString User::profile() const
{
    if(m_profile == ""){
        return "../../src/user.png";
    }
    else{
        qDebug("111111111111123");
        return "file:///"+m_profile;
    }
}

QString User::download() const
{
    return m_downloadFolder;
}
//辅助函数
QString User::getuserfolder(QString& usn)
{
    return QDir::currentPath()+"/userfolder/" + usn;
}
//辅助函数
QString User::getuserfile( QString& path)
{
    return getuserfolder(path) + "/user.json";
}
//辅助函数
QJsonObject User::makejsonobj(){
    QJsonObject obj ;
    obj.insert(USN,QJsonValue(m_name));
    obj.insert(PSW,QJsonValue(m_password));
    obj.insert(DOWNF,QJsonValue(m_downloadFolder));
    obj.insert(PRO,QJsonValue(m_profile));
    return obj;
}
//辅助函数
QJsonObject User::readjsonobj(const QString& filename)
{
    QJsonObject obj;
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly))
    {
        QJsonDocument jsonDoc=QJsonDocument::fromJson(file.read(file.size()));
        obj = jsonDoc.object();
        file.close();
    }
    return obj;
}

//辅助函数
void User::saveMesage()
{
    qDebug()<<m_name;
    QString  path = getuserfile(m_name);
    QFile file(path);
    if(file.exists()){
        file.remove();
    }
    if(!file.open(QIODevice::ReadWrite)) {
        emit sendMsg("cannot save user imformation");
    }
    QJsonDocument doc;
    QJsonObject jsonobj = makejsonobj();
    doc.setObject(jsonobj);
    file.write(doc.toJson());
    file.close();
    emit nameChanged();
    emit profileChanged();
    emit downloadChanged();
}


void User::setCharater(QString& username){
    QString path =getuserfile(username);
    QJsonObject obj=  readjsonobj(path);
    if(obj.contains(DOWNF))
    {
        m_downloadFolder = obj.value(DOWNF).toString();
    }
    if(obj.contains(PSW))
    {
        m_password = obj.value(PSW).toString();
    }
    if(obj.contains(USN))
    {
        m_name = obj.value(USN).toString();
    }
    if(obj.contains(PRO))
    {
        m_profile = obj.value(PRO).toString();
    }
    set_history_bookmark();
    emit nameChanged();
    emit profileChanged();
    emit downloadChanged();
}

void User::createUser(  QString usn,const QString psw)
{
    if(iflogin){
        emit sendMsg("you should log out first");
        return;
    }
    if(usn == "default_user")
    {
        emit sendMsg("you can not create a user called " +usn);
        return;
    }
    QString path = getuserfolder(usn);
    QDir dir;
    if(dir.exists(path))
    {
        emit sendMsg(usn + " has been created before");
    }
    else
    {

        dir.mkdir(path);
        // somthing must be add
        m_name   = usn;
        m_password = psw;
        m_downloadFolder = downloadPath;//默认设置
        m_profile = "";
        saveMesage();
        //创建用户的时候进行一次
        set_history_bookmark();
        sendMsg("Welcome " + m_name + " for your first login");
        iflogin = true;
        emit logStatusChanged();
    }
}


void User::set_history_bookmark()
{
    if(m_bookmarkManager != NULL){
        delete m_bookmarkManager;
        m_bookmarkManager = NULL;
    }
    if(m_historyManager != NULL){
        delete m_historyManager;
        m_historyManager = NULL;
    }
    if(m_downloadManager!=NULL){
        delete m_downloadManager;
        m_downloadManager=NULL;
    }
    m_bookmarkManager = new BookmarkManager(m_name);
    m_historyManager = new HistoryManager(m_name);
    m_downloadManager=new DownLoadManager(m_name);
    emit userChanged();
}

void User::changepassword(QString str){
    m_password = str;
    saveMesage();
}

void User::changeUserName(QString name)
{
    if(!iflogin){
        sendMsg("Yyou are not allowed to change the name of default user");
        return;
    }
    QDir dir;
    if(dir.exists(getuserfolder(name))){
        sendMsg(name + "has exist, you are not allowed to change this name");
        return;
    }
    //you need to close the file and then change the user name
    else{
        //        if(m_bookmarkManager != NULL){
        //            delete m_bookmarkManager;
        //            m_bookmarkManager = NULL;
        //        }
        //        if(m_historyManager != NULL){
        //            delete m_historyManager;
        //            m_historyManager = NULL;
        //        }
        if( dir.rename(getuserfolder(m_name) ,getuserfolder(name) ))
        {
            m_name = name;
            QString fullpath = "";
            if(m_profile != "")
            {
                QStringList list = m_profile.split("/");
                QString path = list.value(list.length() - 1);
                fullpath = getuserfolder(m_name) + "/" + path;
            }
            m_profile = fullpath;
            saveMesage();
            emit sendMsg("Your name changed into " + name);
        }
        else
        {
            qDebug()<<"nonono   " << getuserfolder(m_name) << "   " << getuserfolder(name);
        }
        //        m_historyManager = new HistoryManager(m_name);
        //        m_bookmarkManager = new BookmarkManager(m_name);
    }
}


void User::changeDownloadFolder(QString foldername)
{
    foldername = foldername.remove(0,8);
    if(!iflogin){
        qDebug()<<"do not login";
        emit sendMsg("You are not allowed to change download path of default_user");
        return;
    }
    else
    {
        qDebug()<<"do  login";
        emit sendMsg("success");
        m_downloadFolder = foldername;
        emit downloadChanged();
        saveMesage();
    }
}


void User::changeprofile(QString filename)
{
    filename = filename.remove(0,8);
    if(!iflogin){
        emit sendMsg("you are not allowed to changed default user's profile");
        return;
    }
    if(!QFile::exists(filename)){
        emit sendMsg("cannot get the profile file needed");
        return;
    }
    else{
        QStringList list = filename.split("/");
        QString path = list.value(list.length() - 1);
        QString fullpath = getuserfolder(m_name) + "/" + path;
        if(m_profile != "")
        {
            QFile::remove(m_profile);
        }
        m_profile = fullpath;
        qDebug()<<"dadadadadadada::" << m_profile;
        QFile::copy(filename,fullpath);
        saveMesage();
    }
}


void User::remove_history_bookmark(){
    delete m_historyManager;
    delete m_bookmarkManager;
    delete m_downloadManager;
    m_historyManager = NULL;
    m_bookmarkManager = NULL;
    m_downloadManager=NULL;
}
